package com.xianggu.lock.demo;

import java.util.concurrent.locks.ReentrantLock;

public class TicketSystem {
    private int tickets = 10; // 总票数
    private final ReentrantLock lock = new ReentrantLock(); // 可重入锁

    public void buyTicket() {
        lock.lock(); // 加锁
        try {
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + " 抢到了第 " + tickets-- + " 张票");
            } else {
                System.out.println(Thread.currentThread().getName() + " 抱歉，票已售罄");
            }
        } finally {
            lock.unlock(); // 释放锁
        }
    }

    public static void main(String[] args) {
        TicketSystem ticketSystem = new TicketSystem();

        // 模拟 20 个用户同时抢票
        for (int i = 0; i < 20; i++) {
            new Thread(() -> ticketSystem.buyTicket(), "用户" + i).start();
        }
    }
}